package com.dfdchem.imd.kaiwu.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.activity.base.BaseActivity;
import com.dfdchem.imd.kaiwu.adapter.MainPageAdapter;
import com.dfdchem.imd.kaiwu.constant.RouterPath;
import com.dfdchem.imd.kaiwu.fragment.AlarmFragment;
import com.dfdchem.imd.kaiwu.fragment.CustomDialog;
import com.dfdchem.imd.kaiwu.fragment.HomeFragment;
import com.dfdchem.imd.kaiwu.fragment.ProfileFragment;
import com.dfdchem.imd.kaiwu.fragment.TaskFragment;
import com.dfdchem.imd.kaiwu.interfaces.GlideDownloadListener;
import com.dfdchem.imd.kaiwu.interfaces.OnHttpResponseListener;
import com.dfdchem.imd.kaiwu.manager.DataManager;
import com.dfdchem.imd.kaiwu.manager.GlideManager;
import com.dfdchem.imd.kaiwu.manager.PermissionManager;
import com.dfdchem.imd.kaiwu.model.AlarmCountModel;
import com.dfdchem.imd.kaiwu.model.AppConfig;
import com.dfdchem.imd.kaiwu.model.AppPublish;
import com.dfdchem.imd.kaiwu.model.CommonUri;
import com.dfdchem.imd.kaiwu.model.Resp;
import com.dfdchem.imd.kaiwu.model.User;
import com.dfdchem.imd.kaiwu.util.JSON;
import com.dfdchem.imd.kaiwu.util.Log;
import com.dfdchem.imd.kaiwu.util.RequestUtil;
import com.dfdchem.imd.kaiwu.util.SPUtil;
import com.dfdchem.imd.kaiwu.util.StringUtil;
import com.dfdchem.imd.kaiwu.util.VersionUtil;
import com.king.zxing.Intents;
import com.kongzue.kongzueupdatesdk.v3.UpdateUtil;

import java.util.ArrayList;
import java.util.List;

import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.PageNavigationView;
import me.majiajie.pagerbottomtabstrip.listener.SimpleTabItemSelectedListener;
import pub.devrel.easypermissions.EasyPermissions;

@Route(path = RouterPath.MAIN_ACTIVITY)
public class MainActivity extends BaseActivity implements View.OnClickListener, OnHttpResponseListener, SimpleTabItemSelectedListener, ViewPager.OnPageChangeListener, EasyPermissions.PermissionCallbacks {
    private static final String TAG = "MainActivity";

    private PageNavigationView tab;
    private NavigationController navigationController;
    private ViewPager viewPager;
    private MainPageAdapter mPageAdapter;
    private List<Fragment> mFragments;

    @Autowired
    String url;

    private UpdateUtil updateUtil;

    private static final int request_code_get_user_info = 1;
    private static final int request_code_get_launch_ad = 2;
    public static final int request_code_qr_scan = 3;
    public static final int permission_request_file = 4;
    public static final int request_code_get_alarm_count = 5;
    public static final int request_code_version_check = 6;

    /**
     * 启动这个Activity的Intent
     * @param context
     * @return Intent
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, MainActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = getIntent();

        initView();
        initData();
        initEvent();
        initPermission();
        initPrivacy();
        handleScheme(getIntent().getData());
    }

    @Override
    protected void onResume() {
        Log.d(TAG, "\n onResume <<<<<<<<<<<<<<<<<<<<<<<");
        super.onResume();
        Log.d(TAG, "onResume >>>>>>>>>>>>>>>>>>>>>>>>\n");
    }

    @Override
    public void initView() {
        Log.d(TAG, this.getClass().getSimpleName() + " initView");

        tab = findView(R.id.main_tab);
        viewPager = findView(R.id.main_view_pager);

        navigationController = tab.material()
                .addItem(R.drawable.ic_menu_home, "主页")
                .addItem(R.drawable.icon_bell, "报警")
                .addItem(R.drawable.icon_check_list, "任务")
                .addItem(R.drawable.ic_menu_me, "我")
                .build();

        navigationController.setHasMessage(1, true);
        navigationController.setMessageNumber(2,100);
        navigationController.setHasMessage(3, true);
        navigationController.addSimpleTabItemSelectedListener(this);
        navigationController.setupWithViewPager(viewPager);
    }

    public void setNCBadger(int index, int number, boolean hasMessage) {
        if (number == 0) {
            navigationController.setHasMessage(index, hasMessage);
        } else if (number > 0) {
            navigationController.setMessageNumber(index, number);
        }
    }

    public void setSelect(int position) {
        if (position >= navigationController.getItemCount()) {
            return;
        }
        navigationController.setSelect(position);
    }

    @Override
    public void initData() {
        Log.d(TAG, this.getClass().getSimpleName() + " initData");

        mFragments = new ArrayList<Fragment>();

        HomeFragment homeFragment = HomeFragment.newInstance();
        mFragments.add(homeFragment);
        mFragments.add(AlarmFragment.newInstance());
        mFragments.add(TaskFragment.newInstance());

        ProfileFragment profileFragment = ProfileFragment.newInstance();
        mFragments.add(profileFragment);

        mPageAdapter = new MainPageAdapter(getSupportFragmentManager(), mFragments);
        viewPager.setAdapter(mPageAdapter);

        runThread(TAG + "getUserInfo", new Runnable() {
            @Override
            public void run() {
                RequestUtil.getUserInfo(request_code_get_user_info, MainActivity.this);
            }
        });

        runThread(TAG + "getLaunchAd", new Runnable() {
            @Override
            public void run() {
                RequestUtil.getLaunchAd(request_code_get_launch_ad, MainActivity.this);
            }
        });

        User user = DataManager.getInstance().getUser();
        if (user != null && user.getId() > 0) {
            runThread(TAG + "getAlarmCount", new Runnable() {
                @Override
                public void run() {
                    RequestUtil.getAlarmCount(user.getId(), request_code_get_alarm_count, MainActivity.this);
                }
            });
        }

        // 更新检测
        runThread(TAG + "getUpdate", new Runnable() {
            @Override
            public void run() {
                AppPublish appPublish = new AppPublish();
                appPublish.setPackageName(VersionUtil.getPackageName(getActivity()));
                appPublish.setVersionCode(VersionUtil.getAppVersionCode(getActivity()));
                RequestUtil.versionCheck(appPublish, request_code_version_check, MainActivity.this);
            }
        });
    }

    @Override
    public void initEvent() {
        Log.d(TAG, this.getClass().getSimpleName() + " initEvent");

        viewPager.addOnPageChangeListener(this);
    }

    public void initPermission() {
        if (android.os.Build.VERSION.SDK_INT >=  Build.VERSION_CODES.M) {
            if (!EasyPermissions.hasPermissions(this, PermissionManager.PERMISSIONS)) {
                EasyPermissions.requestPermissions(this, getString(R.string.text_permission_file), PermissionManager.REQUEST_PERMISSIONS, PermissionManager.PERMISSIONS);
            }
        }
    }

    private CustomDialog mDialog = null;
    private void initPrivacy(){
        SPUtil spUtil = new SPUtil(this);
        if (spUtil.getBoolean("IS_PRIVACY_ACCEPT", false)) {
            return;
        }
        String content = "" +
                "本《隐私政策》将向您说明\n" +
                "1.为帮助你浏览推荐、发布信息、互动\n" +
                "交流、注册认证，我们会收集你的部分\n" +
                "必要信息\n" +
                "2.为提供上述服务，我们可能会收集联\n" +
                "络方式、位置、通讯录等部分敏感信\n" +
                "息，你有权拒绝或撒回授权\n" +
                "3.未经你同意，我们不会从第三方获\n" +
                "取、共享或提供你的信息\n" +
                "4.你可以访问、更正、删除你的个人信\n" +
                "息，我们也将提供注销、投诉的方式。\n" +
                "如你点击不同意，我们将仅收集浏览推\n" +
                "荐所必需的信息，不会收集上述敏感信\n" +
                "息，但推荐精准度、互动交流、发布信\n" +
                "息可能会受影响。";
        mDialog = new CustomDialog(this,
                "用户隐私政策概要",
                content,
                "同意", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        spUtil.putBoolean("IS_PRIVACY_ACCEPT", true);
                        if (mDialog != null) {
                            mDialog.dismiss();
                        }
                    }
                },
                "不同意",
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mDialog != null) {
                            mDialog.dismiss();
                        }
                        finish();
                    }
                });
        mDialog.setCancelable(false);
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        Log.d(TAG, "onPermissionsGranted requestCode:"+ requestCode + " perms:"+ perms);
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Log.d(TAG, "onPermissionsDenied requestCode:"+ requestCode + " perms:"+ perms);
        if (!perms.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (int i=0; i< perms.size(); i++) {
                String perm = perms.get(i);
                if (perm.equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    sb.append("读取文件（读取缓存）");
                }
                if (perm.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    sb.append("写入文件（写入缓存）");
                }
                if (perm.equals(Manifest.permission.CAMERA)) {
                    sb.append("相机（二维码扫描）");
                }
                if (perm.equals(Manifest.permission.CALL_PHONE)) {
                    sb.append("拨打电话");
                }
                if (i != perms.size() -1 ){
                    sb.append("\n");
                }
            }

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("提示：");
            builder.setMessage("App运行需要授予如下权限，否则可能无法正常运行：\n" + sb.toString() + "\n是否打开权限设置" );
            builder.setIcon(R.drawable.icon_info);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    try {
                        // 这个适配有问题，咱时不处理
                        PermissionManager.toPermissionSetting(MainActivity.this);
                    } catch (Exception e) {
                        Log.e(TAG, "onPermissionsDenied e:" + e.getMessage());
                    }
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            builder.create().show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "onActivityResult requestCode:" + requestCode + " resultCode:" + resultCode + " data:" + data);
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case request_code_qr_scan:
                if (data != null) {
                    String qr_result = data.getStringExtra(Intents.Scan.RESULT);
                    showShortToast("二维码结果:" + qr_result);
                }
                break;
        }
    }

    @Override
    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
        Log.d(TAG, "onHttpResponse:" + requestCode);
        Log.d(TAG, "resultJson:" + resultJson);
        dismissProgressDialog();
        if (e != null) {
            Toast.makeText(this, "请求失败，" + e.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        switch (requestCode) {
            case request_code_get_user_info:
                Resp<User> respUser = JSON.parseResp(resultJson, User.class);
                if (respUser == null || respUser.getCode() != 200) {
                    Toast.makeText(this, respUser != null ? respUser.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                    return;
                }
                User user = respUser.getData();
                if (user == null) {
                    Toast.makeText(this, "解析异常", Toast.LENGTH_LONG).show();
                    return;
                }
                DataManager.getInstance().saveUser(user);
                break;
            case request_code_get_launch_ad:
                Resp<AppConfig> appConfigResp = JSON.parseResp(resultJson, AppConfig.class);
                if (appConfigResp != null && appConfigResp.getData() != null) {
                    AppConfig appConfig = appConfigResp.getData();
                    if (!StringUtil.isEmpty(appConfig.getValue())) {
                        CommonUri commonUri = JSON.parseObject(appConfig.getValue(), CommonUri.class);
                        if (!StringUtil.isEmpty(commonUri.getImageUrl())) {

                            // 下载图片到本地
                            new GlideManager(this).save(commonUri.getImageUrl(), new GlideDownloadListener() {
                                @Override
                                public void onDownloadSuccess(String fileUri) {
                                    commonUri.setImagePath(fileUri);
                                    new SPUtil(MainActivity.this).putObject("LaunchAd", commonUri);
                                }
                            });
                        }
                    }
                }
                break;
            case request_code_get_alarm_count:

                Resp<AlarmCountModel> resp = JSON.parseResp(resultJson, AlarmCountModel.class);
                if (resp == null || resp.getCode() != 200) {
                    Toast.makeText(getActivity(), resp != null ? resp.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                    return;
                }
                AlarmCountModel alarmCountModel = resp.getData();

                if (alarmCountModel == null) {
                    Toast.makeText(getActivity(), "解析异常", Toast.LENGTH_LONG).show();
                    return;
                }

                navigationController.setMessageNumber(1, alarmCountModel.getTotalAlarm());

                break;
            case request_code_version_check:
                Resp<AppPublish> respAppPublish = JSON.parseResp(resultJson, AppPublish.class);
                if (respAppPublish == null || respAppPublish.getCode() != 200) {
                    Toast.makeText(getActivity(), respAppPublish != null ? respAppPublish.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                    return;
                }
                AppPublish appPublish = respAppPublish.getData();
                if (appPublish == null) {
                    return;
                }

                // 适配内网地址
                if (appPublish.getPackageUrl().startsWith("/Fe/Files/Index")) {
                    appPublish.setPackageUrl(RequestUtil.URL_BASE_API + appPublish.getPackageUrl());
                }

                //初始化
                if (updateUtil == null) {
                    updateUtil = new UpdateUtil(MainActivity.this);
                }

                updateUtil.setOnUpdateStatusChangeListener(null)
                        .showDownloadNotification("正在下载更新", "正在下载更新 " +  appPublish.getTitle() + "...")
                        .showDownloadProgressDialog("正在下载更新", "后台下载", "取消")
                        .start(appPublish.getPackageUrl(),                       //开始下载
                                "发现更新",
                                appPublish.getDes(),
                                "确定",
                                "取消",
                                null,
                                false
                        );
                break;
        }
    }

    @Override
    public void onSelected(int index, int old) {
        Log.d(TAG, "onSelected index:" + index + " old:" + old);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        Log.d(TAG, "onPageSelected position:" + position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        Log.d(TAG, "onPageScrollStateChanged state:" + state);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("退出：");
                builder.setMessage("确定退出应用吗?");
                builder.setIcon(R.drawable.icon_info);
                builder.setPositiveButton("是的", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MainActivity.this.finish();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

                builder.create().show();
                return true;
            default:
                break;
        }

        return super.onKeyUp(keyCode, event);
    }


}